﻿using System;
using System.Collections;
using ExFlash.Records;

namespace ExFlash.Filters
{
    public class ConvolutionFilter : ISwfSerializable
    {
        private const int ClampIndex = 6;
        private const int PreserveAlphaIndex = 7;
        
        private readonly BitArray _flags;
        private const int BitArraySize = 8;

        public Byte MatrixX
        {
            get;
            private set;
        }

        public Byte MatrixY
        {
            get;
            private set;
        }

        public float Divisor
        {
            get;
            private set;
        }

        public float Bias
        {
            get;
            private set;
        }

        public float[] Matrix
        {
            get;
            private set;
        }

        public RGBARecord DefaultColor
        {
            get;
            private set;
        }

        public Boolean Clamp
        {
            get
            {
                return _flags[ClampIndex];
            }
            protected set
            {
                _flags[ClampIndex] = value;
            }
        }

        public Boolean PreserveAlpha
        {
            get
            {
                return _flags[PreserveAlphaIndex];
            }
            protected set
            {
                _flags[PreserveAlphaIndex] = value;
            }
        }

        public ConvolutionFilter()
        {
            _flags = new BitArray(BitArraySize);
        }
        
        #region ISwfSerializable Members

        public void SwfDeserialize(BinaryBitReader reader)
        {
            MatrixX = reader.ReadByte();

            MatrixY = reader.ReadByte();

            Divisor = reader.ReadSingle();

            Bias = reader.ReadSingle();

            Matrix = new float[MatrixX * MatrixY];

            for (int i = 0; i < MatrixX * MatrixY; i++)
            {
                Matrix[i] = reader.ReadSingle();
            }

            DefaultColor = new RGBARecord();
            DefaultColor.SwfDeserialize(reader);

            reader.SkipBits(ClampIndex);
            Clamp = reader.ReadBoolean();
            PreserveAlpha = reader.ReadBoolean();
            reader.AlignBits();
        }

        public void SwfSerialize(byte[] arr, ref int offset)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
